// taskQueue.js

class TaskManager {
	constructor() {
		this.queue = []
		this.currentJob = null
		this.timer = null
		this.completionListeners = []
		this.startPolling()
	}

	// 创建新任务
	createJob(name) {
		return {
			jobNo: `${name}_${Date.now()}`,
			name,
			actions: [],
			execIndex: 0,
			status: 0 // 0-pending, 1-running, 2-completed
		}
	}

	// 添加任务到队列
	addJob(job) {
		this.queue.push(job)
		this.triggerQueue()
	}

	// 添加动作到任务
	addAction(job, action) {
		// console.log(JSON.stringify(job));
		// console.log(JSON.stringify(action));
		if (job.status === 0) {
			job.actions.push(action)
		} else {
			console.error('Cannot add action to running job')
		}
	}

	// 执行任务
	async executeJob(job) {
		job.status = 1
			// console.log(job.execIndex);
			// console.log(job.actions);
		try {
			while (job.execIndex < job.actions.length) {
				const action = job.actions[job.execIndex]
				if (action.type === 'job') {
					await this.executeJob(action.execution)
				} else {
					if (!action.async) {
						action.execution()
					} else {
						// console.log(JSON.stringify(action.execution));
						await action.execution()
					}
				}
                
				job.execIndex++
				console.log(job);
			}
			job.status = 2
		} catch (error) {
			console.error('Job execution failed:', error)
			job.status = 3 // 3-failed
		} finally {
			this.removeJob(job)
			this.triggerQueue()
		}
	}

	// 移除任务
	removeJob(job) {
		this.queue = this.queue.filter(j => j !== job)
	}

	// 触发队列执行
	triggerQueue() {
		// console.log(this.currentJob);
		// console.log(this.queue.length);
		if (!this.currentJob && this.queue.length > 0) {
			this.currentJob = this.queue[0]
			this.executeJob(this.currentJob)
		}
	}

	// 启动轮询检查
	startPolling() {
		this.timer = setInterval(() => {
			if (!this.currentJob && this.queue.length > 0) {
				this.triggerQueue()
			} else {
				this.currentJob = null;
			}
		}, 100)
	}

	// 停止轮询
	stopPolling() {
		this.queue = []
		this.currentJob = null
		this.completionListeners = []
		clearInterval(this.timer)
	}
}

Vue.mixin({
	beforeDestroy() {
		taskManager.stopPolling();
	}
});

// 导出实例
export const taskManager = new TaskManager()